//
//  HookCommand.m
//  Staff
//
//  Created by caiyao on 1/6/15.
//
//

#import "HookCommand.h"
#import "NSString+EXT.h"
#import "Constants.h"
#import "DictionaryUtility.h"

@implementation HookCommand

+ (NSDictionary *)handleNonHTTPRequest:(NSURLRequest*)request
{
    
    NSString *passedURI = [[request URL] absoluteString];
    passedURI = [passedURI substringWithRange:NSMakeRange([NON_HTTP_SCHEME length],[passedURI length] - [NON_HTTP_SCHEME length])];
    DebugLog(@"URI to process: %@",passedURI);
    
    passedURI = [NSString urlValueDecode:passedURI];
    NSMutableDictionary *paramDictionary = [self dictionaryFromMessage:passedURI];
    
    return paramDictionary;
}

+ (NSMutableDictionary *)dictionaryFromMessage:(NSString*)message
{
    
    DebugLog(@"message to process: %@",message);
    NSArray *params = [message componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&="]];
    
    NSMutableDictionary *paramDictionary = [DictionaryUtility indexKeyedDictionaryFromArray:params];
    
    return paramDictionary;
}

+ (NSDictionary *)getDictionaryFromMessage:(NSString*)message
{
    NSMutableDictionary *paramDictionary = [self dictionaryFromMessage:message];
    
    return paramDictionary;
}

+ (HookCommand *)parserHookCommandFromRequest:(NSURLRequest *)request {
    HookCommand *hookCommand = [[HookCommand alloc] init];
    
    NSDictionary *commandDic = [self handleNonHTTPRequest:request];
    
    hookCommand.functionParamsDic = [NSDictionary dictionaryWithDictionary:commandDic];
    
    hookCommand.functionName = [commandDic objectForKey:@"function"];
    hookCommand.dataJS = [commandDic objectForKey:@"datajs"];
    hookCommand.callbackJS = [commandDic objectForKey:@"callbackjs"];
    hookCommand.eventJS = [commandDic objectForKey:@"eventjs"];
    
    return hookCommand;
}

@end
